"use client";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import type { FC } from "react";
import {
  StyleProvider,
  legacyLogicalPropertiesTransformer,
} from "@ant-design/cssinjs";
import { produce } from "immer";
import Education from "../education/edit";
import Project from "../project/edit";
import Work from "../work/edit";
import School from "../school/edit";
import Certificate from "../certificate/edit";
import Hobby from "../hobby/edit";
import Skills from "../skills/edit";
import Internship from "../internship/edit";
import Custom from "../custom/edit";
import Selfevaluation from "../selfevaluation/edit";
import contentStyle from "../../index.module.scss";
import styles from "./index.module.scss";
import notification from "@/app/components/hooks/useNotification";
import { getInitContent } from "@/app/utils";
import Confirm from "@/app/components/Confirm";
import { useContentStore } from "@/src/providers/content-store-provider";
import { useCommonStore } from "@/src/providers/common-store-provider";
import useServerStore from "@/app/components/hooks/useServerStore";
import { useCustomizationStore } from "@/src/providers/customization-store-provider";
import { Form, Input } from "antd";
import classNames from "classnames";
import BottomButton from "@/app/components/BottomButton";
import { useRouter } from "next/navigation";

interface IndexProps {
  type: Sections;
  onChangeCurrent?: () => void;
}

const Index: FC<IndexProps> = ({ type, onChangeCurrent, ...props }) => {
  const router = useRouter();

  const { customization, updateSectionOrder } = useCustomizationStore(
    (state) => state
  );
  const { updateSection, addContent, deleteContent, content } = useContentStore(
    (state) => state
  );
  const key = useId();
  const [loading, setLoading] = useState(false);
  const serverStore = useServerStore();
  const { index, setCurrentTab, isMobile } = useCommonStore((state) => state);
  const data = content[type];
  const oldFormData = useRef<any>(null);
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue(data?.entries?.[index] || {});
    if (data?.entries?.[index]) {
      oldFormData.current = data?.entries?.[index];
    }
    if (!data) {
      addContent(
        getInitContent(type),
        type,
        customization,
        updateSectionOrder,
        content
      );
    }
    const siderbar = document.getElementById("siderbar");
    if (siderbar) {
      siderbar.style.display = "none";
    }
  }, []);

  const reset = () => {
    let isDelete = false;
    const d = produce(content, (draft) => {
      if (draft) {
        if (Object.keys(oldFormData.current || {}).length) {
          draft[type].entries[index] = oldFormData.current;
        } else {
          draft[type].entries = draft[type].entries.filter((_, i) => i < index);
        }
        if (draft[type].entries.length === 0 && !oldFormData.current) {
          isDelete = true;
          delete draft[type];
        }
      }
    });
    if (isDelete) {
      deleteContent(type);
    } else {
      updateSection(d[type], type);
    }
  };
  const clearDate = (dateObj) => {
    if (dateObj?.startDate) {
      if (!dateObj.startDate.year) {
        delete dateObj.startDate.year;
      }
      if (!dateObj.startDate.month) {
        delete dateObj.startDate.month;
      }
    }
    if (dateObj?.endDate) {
      if (!dateObj.endDate.year) {
        delete dateObj.endDate.year;
      }
      if (!dateObj.endDate.month) {
        delete dateObj.endDate.month;
      }
      if (!dateObj.endDate.untilToday) {
        delete dateObj.endDate.untilToday;
      }
    }
    if (!Object.keys(dateObj?.startDate || {}).length) {
      dateObj.startDate = null;
    }
    if (!Object.keys(dateObj?.endDate || {}).length) {
      dateObj.endDate = null;
    }
  };
  return (
    <StyleProvider
      transformers={[legacyLogicalPropertiesTransformer]}
      hashPriority="high"
    >
      <div className={classNames(styles.contentItemEdit, contentStyle.card)}>
        <Form
          layout="vertical"
          form={form}
          onValuesChange={(value, values) => {
            if (
              value.description &&
              value.description === data?.entries?.[index]?.description
            ) {
              return;
            }
            clearDate(values);
            updateSection(
              produce(content[type], (draft) => {
                if (draft) {
                  if (!values.key && !values.id) {
                    values.key = key;
                  }
                  draft.entries[index] = values;
                }
              }),
              type
            );
          }}
        >
          {type === "education" ? (
            <Education displayName={data?.displayName}></Education>
          ) : null}
          {type === "project" ? (
            <Project displayName={data?.displayName}></Project>
          ) : null}
          {type === "work" ? (
            <Work displayName={data?.displayName}></Work>
          ) : null}
          {type === "certificate" ? (
            <Certificate displayName={data?.displayName}></Certificate>
          ) : null}
          {type === "skills" ? (
            <Skills displayName={data?.displayName}></Skills>
          ) : null}
          {type === "school" ? (
            <School displayName={data?.displayName}></School>
          ) : null}
          {type === "internship" ? (
            <Internship displayName={data?.displayName}></Internship>
          ) : null}
          {type === "selfevaluation" ? (
            <Selfevaluation displayName={data?.displayName}></Selfevaluation>
          ) : null}
          {type === "custom" ? (
            <Custom {...props} displayName={data?.displayName}></Custom>
          ) : null}
          {type === "hobby" ? (
            <Hobby {...props} displayName={data?.displayName}></Hobby>
          ) : null}

          <Form.Item name={"id"} hidden>
            <Input></Input>
          </Form.Item>
          <Form.Item name={"key"} hidden>
            <Input></Input>
          </Form.Item>
          <Form.Item name={"isHidden"} hidden>
            <Input></Input>
          </Form.Item>
          <Form.Item name={"contentId"} hidden>
            <Input></Input>
          </Form.Item>
        </Form>

        <BottomButton
          loading={loading}
          onCancel={() => {
            if (isMobile) {
              router.back();
            } else {
              reset();
              setCurrentTab("content");
            }
          }}
          onDelete={async () => {
            Confirm({
              content: "确认删除该条数据？",
              onOk: async () => {
                if (content[type]) {
                  const formData = await form.getFieldsValue();
                  await serverStore.delEntryFn(formData, content[type]);
                }
              },
            });
          }}
          onConfirm={async () => {
            const formData = await form.validateFields();
            clearDate(formData);
            let res;
            if (type === "selfevaluation" || type === "custom") {
              if (!formData.description) {
                notification({
                  message: "保存内容不能为空",
                });
                return;
              }
            }
            if (type === "skills" || type === "certificate") {
              if (!formData.description && !formData.list?.length) {
                notification({
                  message: "保存内容不能为空",
                });
                return;
              }
            }
            try {
              if (content[type].id) {
                setLoading(true);
                if (formData.id) {
                  res = await serverStore.editEntryFn(formData);
                } else {
                  res = await serverStore.addEntryFn(formData, content[type]);
                }
                setLoading(false);
              } else {
                setLoading(true);
                res = await serverStore.save(content[type]);
                setLoading(false);
                console.log(res);
              }
            } catch {
              setLoading(false);
            }
          }}
        />
      </div>
    </StyleProvider>
  );
};

export default Index;
